﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection; 

using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Automapping;

using Domain.Model.Abstract;
using Domain;

namespace DataAccess.Utils
{
    public class SessionProvider
    {
        private static ISessionFactory SessionFactory;

        private static ISessionFactory BuildSessionFactory
        {
            get
            {
                if (SessionFactory == null)
                {

                    SessionFactory = Fluently.Configure()
                    .Database(DataAccessConfiguration.MsSqlServerAccessConfiguration())
                    // passing the AutoMappingModel
                    .Mappings(m => m.AutoMappings.Add(Domain.Model.Mapping.DomainMapping.CreateMappings()))
                    // generate the database tables
                    //.ExposeConfiguration(ExportSchema)
                    // finally build the session
                    .BuildSessionFactory();                                             
                }

                return SessionFactory;
            }
        }

        private static void ExportSchema(Configuration Config)
        {
            new SchemaExport(Config).SetOutputFile(@"C:\temp\PortfolioManagementSystem_DB.sql").Create(false, true);
        }

        /// <summary>
        /// Opens a database Session.
        /// </summary>
        /// <returns></returns>
        public static ISession OpenSession()
        {
            return BuildSessionFactory.OpenSession();
        }

        /// <summary>
        /// Closes the current database session.
        /// </summary>
        public static void CloseSession()
        {
            SessionFactory.Close();
        }
    }
}